// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile, getUserDetail } from '@/api/user'
// import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, val) {
    state.token = val
    setToken(val)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 创建登录actions
  async userLogin(context, params) {
    // 调用接口，通过context传参调用内部mutations
    const res = await login(params)
    context.commit('setToken', res.data)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getUserProfile()
    const user = await getUserDetail(res.data.userId)
    // console.log(user)
    // console.log(res)
    context.commit('setUserInfo', { ...res.data, ...user.data })
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

